package com.tlgen.spring.utils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tlgen.spring.annotation.Value;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class YmlUtils {

    public static Map<String, Object> readYml() {
        Map<String, Object> data = Maps.newHashMap();
        Yaml yaml = new Yaml();
        String userDir = System.getProperty("user.dir");
        try (InputStream inputStream = Files.newInputStream(Paths.get(userDir + "\\src\\main\\resources\\application.yml"))) {
            data = yaml.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    public static Object getValueFromYml(Value annotation) {
        String value = annotation.value();
        String name = value.substring(value.indexOf("{") + 1, value.indexOf("}"));
        String[] split = name.split("\\.");
        List<Object> objects = Lists.newArrayList();
        getValueByYml(split, 0, objects);
        return objects.get(objects.size() - 1);
    }

    public static void getValueByYml(String[] split, int i, List<Object> objects) {
        Map<String, Object> map = YmlUtils.readYml();
        if (i > 0) {
            map = (Map<String, Object>) objects.get(objects.size() - 1);
        }
        objects.add(map.get(split[i]));
        if (Objects.nonNull(map.get(split[i])) && map.get(split[i]).getClass().getTypeName().contains("LinkedHashMap")) {
            i++;
            if (i < split.length) {
                getValueByYml(split, i, objects);
            }
        }
    }

}
